package com.ufo.utils.sequence;


import java.io.PrintStream;

import org.safehaus.uuid.UUID;
import org.safehaus.uuid.UUIDGenerator;

public class Sequence {
	private static final int MAX_DEPTS_PER_LEVEL = 100;
	private static final int MAX_GROUP_PER_LEVEL = 100;
	private static final int MAX_PERSONS_PER_LEVEL = 1000;
	private static final int base = 100000;
	private static long millis = 0L;

	private static long counter = 0L;

	private static long old = 0L;
	private static final int MAX_TOPIC_NUMBER = 1000000;
	private static final int MAX_TOPICCHILD_NUMBER = 1000;
	private static final int MAX_TITLE_COUNT = 10000;
	private static final int MAX_SHORTMESSAGE_NUMBER = 9999;
	private static char[] HandlerChars = { 'A', 'B', 'C' };

	private static char baseChar = 'A';
	private static final char maxChar = 'Z';

	public static synchronized String getSequence() throws SequenceException {
		UUIDGenerator gen = UUIDGenerator.getInstance();
		UUID uuid = gen.generateTimeBasedUUID();

		String uuidStr = uuid.toString();
		String[] uuidParts = uuidStr.split("-");
		StringBuffer builder = new StringBuffer();
		builder.append(uuidParts[2]);
		builder.append("-");
		builder.append(uuidParts[1]);
		builder.append("-");
		builder.append(uuidParts[0]);
		builder.append("-");
		builder.append(uuidParts[3]);
		builder.append("-");
		builder.append(uuidParts[4]);

		return builder.toString();
	}

	public static synchronized String getTimeSequence() throws SequenceException {
		long result = System.currentTimeMillis();
		if (result == millis) {
			old += 1L;
			if (old >= 100000L)
				throw new SequenceException("It had exceed the maxium sequence in this moment.");
			result = millis * 100000L + old;
		} else {
			millis = result;
			result *= 100000L;
			old = 0L;
		}
		return new StringBuffer().append(result).toString();
	}

	public static synchronized long getSequenceTimes() {
		try {
			long rtn = System.currentTimeMillis();
			while (rtn == counter) {
				Thread.currentThread();
				Thread.sleep(2L);
				rtn = System.currentTimeMillis();
			}
			counter = rtn;
			return rtn;
		} catch (InterruptedException ie) {
		}
		return System.currentTimeMillis();
	}

	public static void main(String[] args) throws Exception {
		System.out.println(getSequenceTimes());
	}
}